package com.jian.mall.produce.service.impl;

import com.jian.mall.produce.vo.json.CatalogLevel2;
import com.jian.mall.produce.vo.json.CatalogLevel3;
import com.jian.mall.produce.vo.json.CatalogVo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jian.mall.common.utils.PageUtils;
import com.jian.mall.common.utils.Query;

import com.jian.mall.produce.dao.CategoryDao;
import com.jian.mall.produce.entity.CategoryEntity;
import com.jian.mall.produce.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }
    @Cacheable("category-cache")
    @Override
    public List<CategoryEntity> listWithTree() {
        // 查询所有标签
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        return entityList.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .peek(categoryEntity -> categoryEntity.setChild(getChild(categoryEntity, entityList)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 判断是否能删除,是否有依赖项

        // 开启逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCategoryPath(Long attrGroupId) {
        List<Long> path = getParentPath(attrGroupId, new ArrayList<>());
        Collections.reverse(path);
        return path.toArray(new Long[path.size()]);
    }

    @Override
    public List<CategoryEntity> getLevel1Category() {
        List<CategoryEntity> level = baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("cat_level", 1));
        return level;
    }

    @Override
    public CatalogVo<List<CatalogLevel2>> getCatalogJsonVo() {
        CatalogVo<List<CatalogLevel2>> vo = new CatalogVo<>();

        List<CategoryEntity> tree = categoryService.listWithTree();

        tree.forEach(t -> {
            AtomicReference<Long> catId = new AtomicReference<>(0L);
            // catalog 1
            List<CategoryEntity> cat2 = t.getChild();
            List<CatalogLevel2> catalog2List = new ArrayList<>();
            if (cat2 != null && cat2.size() > 0) {
                cat2.forEach(c2 -> {
                    if (catId.get() == 0L)
                        catId.set(c2.getParentCid());
                    // catalog 2
                    CatalogLevel2 level2 = new CatalogLevel2();
                    level2.setCatalog1Id(c2.getParentCid());
                    level2.setName(c2.getName());
                    level2.setId(c2.getCatId());

                    List<CategoryEntity> cat3 = c2.getChild();
                    if (cat3 != null && cat3.size() > 0) {
                        // catalog 3 这边收集成cat3的list返回给cat2成员属性
                        List<CatalogLevel3> level3s = cat3.stream().map(c3 -> {
                            CatalogLevel3 level3 = new CatalogLevel3();
                            level3.setCatalog2Id(c3.getParentCid());
                            level3.setName(c3.getName());
                            level3.setId(c3.getCatId());
                            return level3;
                        }).collect(Collectors.toList());
                        // 设置catalog2的catalog3属性
                        level2.setCatalog3List(level3s);
                    }
                    // 每遍历一次 收集一个完整的catalog2到外层中
                    catalog2List.add(level2);
                });
            }
            // 一整个catalog2List 放入到vo中
            vo.put(catId.get().toString(), catalog2List);
        });
        return vo;
    }

    private List<Long> getParentPath(Long attrGroupId, List<Long> path) {
        path.add(attrGroupId);
        CategoryEntity categoryEntity = baseMapper.selectById(attrGroupId);
        if (categoryEntity.getParentCid() != 0) {
            getParentPath(categoryEntity.getParentCid(), path);
        }
        return path;
    }

    private List<CategoryEntity> getChild(CategoryEntity father, List<CategoryEntity> all) {
        if (father == null) return null;
        return all.stream()
                .filter(categoryEntity ->
                        father.getCatId() != null && categoryEntity.getParentCid().equals(father.getCatId()))
                .peek(categoryEntity -> categoryEntity.setChild(getChild(categoryEntity, all)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }
}